package com.anzym.android.kegdroiddisplay;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class KegDroidStatsFragment extends Fragment {
	
	private String TAG = "KegDroidStatFragement";
	
	private View view;
	private KegDroidData mKdData[];
	
	private TextView kegDroid;
	private TextView numBeersServed;
	private TextView numGallonsServed;
	private TextView numDrinkersServed;
	
	
	public KegDroidStatsFragment(KegDroidData[] mKegDroidData) {
		this.mKdData = mKegDroidData;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		view = inflater.inflate(R.layout.kegdroidstats, container, false);
		
		//Log.d(TAG, "Setting Up Stats data");
		
		kegDroid = (TextView) view.findViewById(R.id.stats_title);
		
		numBeersServed = (TextView) view.findViewById(R.id.number_of_drinks);
		numBeersServed.setText("0");
		numGallonsServed = (TextView) view.findViewById(R.id.number_of_gallons);
		numGallonsServed.setText("0");
		numDrinkersServed = (TextView) view.findViewById(R.id.number_of_unique_drinkers);
		numDrinkersServed.setText("0");
		
		return view;
	}

	public void updateStats(final int kd) {
		getActivity().runOnUiThread(new Runnable() {
			public void run() {
				String kegTitle = null;
				try {
				
					kegDroid.setText(mKdData[kd].getDroidName());
					
					numBeersServed.setText(Integer.toString(mKdData[kd].getNumBeersServed()));
					numGallonsServed.setText(Double.toString(mKdData[kd].getNumGallonsServed()));
					numDrinkersServed.setText(Integer.toString(mKdData[kd].getNumDrinkersServed()));
					//Log.d(TAG, "invalidating the view");
					view.postInvalidate();
					
				}catch (Exception e) {
					Log.e(TAG, "Exception: " + e);
				}
			}
		});
	}
	
	public 
	
	
	class KegDroidStatsRunner implements Runnable {
    	public void run() {
    		while (!Thread.currentThread().isInterrupted()) {
    			try {
    				Log.d(TAG,"New data");
    				for (int kd = 0; kd < mKdData.length; kd++) {
    					updateStats(kd);
    					Thread.sleep(5000);
    				}
    				
    			} catch (Exception e) {
    				Log.e(TAG, "Exception " + e);
    			}
    		}
    	}
    }
}
